<?php

namespace App\Http\Controllers;

use App\Business\BLL\Personal;
use App\Business\BLL\QqMap;
use App\Business\BLL\ReservationBLL;
use App\Business\BLL\SectBLL;
use App\Jobs\SendReservationReject;
use App\Jobs\SendReservationSuccess;
use App\Models\Reservation;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ReservationController extends Controller
{
    function list() {
        $pn = request()->input('pn', config('api.page_num'));
        $status = request()->input('status', '');
        $area = request()->input('area', '');
        $score = request()->input('score', '');
        $sDate = request()->input('sdate', '');
        $eDate = request()->input('edate', '');
        $city = request()->input('city', '');
        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';

        $column = ['reservations.id',
            'usera.name as usera_name',
            'usera.nickname as usera_nickname',
            'usera.head_img as usera_head_img',
            'userb.name as userb_name',
            'userb.nickname as userb_nickname',
            'userb.head_img as userb_head_img',
            'reservations.game_datetime',
            'reservations.type',
            'reservations.status',
            'reservations.view',
            'reservations.area',
            'reservations.address',
        ];
        $list = Reservation::join('wechat_users as usera', function ($join) {
            $join->on('reservations.play_a', '=', 'usera.id');
        })
            ->leftJoin('wechat_users as userb', function ($join) {
                $join->on('reservations.play_b', '=', 'userb.id');
            })
            ->where('reservations.city', 'like', $city)
            ->where('status', '!=', 0)
            ->where('status', '!=', 30);
        if ($status == 'wait') {
            $list = $list->whereNull('reservations.play_b');
            $sDate = strval($sDate . ' 00:00:00');
            $eDate = strval($eDate . ' 23:59:59');
            if ($area != "" && $area != '全部') {
                $list = $list->where('reservations.area', $area);
            }
            $list = $list->where('reservations.score', '>=', $score);
            $list = $list->whereBetween('reservations.game_datetime', [$sDate, $eDate]);
        } else {
            $list = $list->whereNotNull('reservations.play_b');
        }
        $list = $list->orderBy('game_datetime', 'desc')
            ->paginate($pn, $column);

        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    public function myList()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $sectId = request()->input('sect_id', 0);
        $userId = request()->input('user_id', 0);
        $sort = request()->input('sort', 'desc');
        $status = request()->input('status', '100');

        $column = ['reservations.id',
            'usera.name as usera_name',
            'usera.nickname as usera_nickname',
            'usera.head_img as usera_head_img',
            'userb.name as userb_name',
            'userb.nickname as userb_nickname',
            'userb.head_img as userb_head_img',
            'reservations.game_datetime',
            'reservations.type',
            'reservations.status',
            'reservations.view',
            'reservations.area',
            'reservations.address',
        ];

        $list = Reservation::join('wechat_users as usera', function ($join) {
            $join->on('reservations.play_a', '=', 'usera.id');
        })
            ->leftJoin('wechat_users as userb', function ($join) {
                $join->on('reservations.play_b', '=', 'userb.id');
            })
            ->whereRaw("((reservations.type = 1 and (play_a=$userId or play_b=$userId)) or (reservations.type = 2 and (play_a=$sectId or play_b=$sectId)))");

        if ($status == "100") {
            $list->where('status', '!=', 0);
        } else {
            $list->where('status', $status);
        }

        $list = $list->orderBy('game_datetime', $sort)
            ->paginate($pn, $column);

        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    public function start()
    {
        $playA = request()->input('play_a', 0);
        $type = request()->input('type', 1);
        $playB = request()->input('play_b', 0);
        $gameDatetime = request()->input('game_time', 0);
        $address = request()->input('address', '');
        $contact = request()->input('contact');
        $desc = request()->input('desc', '');
        $area = request()->input('area');
        $score = request()->input('score', 0);

        $limit = Carbon::now()->addWeek();
        if ($limit->lte($gameDatetime)) {
            return response()->json(['recode' => 0, 'msg' => '只能约定一周内的比赛']);
        }
        $game = new Reservation;
        $game->type = $type;
        $game->game_datetime = $gameDatetime;
        $game->address = $address;
        $game->contact = $contact;
        $game->desc = $desc;
        $game->area = $area;
        $game->score = $score;

        if ($type == 1) {
            $playABLL = new Personal($playA);
            if ($playB != 0) {
                $playBBLL = new Personal($playB);
            } else {
                $playBBLL = null;
            }
        } else {
            $playABLL = new SectBLL($playA);
            if ($playB != 0) {
                $playBBLL = new SectBLL($playB);
            } else {
                $playBBLL = null;
            }
        }
        $reservation = new ReservationBLL;
        $res = $reservation->startReservation($playABLL, $playBBLL, $game);

        if ($res['status']) {
            return response()->json(['recode' => 1, 'id' => $res['id'], 'msg' => $res['msg']]);
        } else {
            return response()->json(['recode' => 0, 'msg' => $res['msg']]);
        }

    }

    public function info()
    {
        $column = ['reservations.id',
            'usera.id as usera_id',
            'usera.name as usera_name',
            'usera.nickname as usera_nickname',
            'usera.head_img as usera_head_img',
            'usera.point as usera_point',
            'userb.id as userb_id',
            'userb.name as userb_name',
            'userb.nickname as userb_nickname',
            'userb.head_img as userb_head_img',
            'userb.point as userb_point',
            'reservations.game_datetime',
            'reservations.address',
            'reservations.contact',
            'reservations.desc',
            'reservations.type',
            'reservations.status',
            'reservations.area',
            'reservations.score',

        ];

        $id = request()->input('game_id', 0);
        $geme = Reservation::find($id);
        if ($geme) {
            $geme->view += 1;
            $geme->save();
        } else {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }

        $game = Reservation::join('wechat_users as usera', function ($join) {
            $join->on('reservations.play_a', '=', 'usera.id');
        })
            ->leftJoin('wechat_users as userb', function ($join) {
                $join->on('reservations.play_b', '=', 'userb.id');
            })
            ->where('reservations.id', $id)
            ->select($column)
            ->first();

        if ($game) {
            return response()->json(['recode' => 1, 'info' => $game]);
        } else {
            return response()->json(['recode' => 0, 'msg' => '未找到挑战']);
        }
    }

    public function setAbnormal()
    {
        $gameId = request()->input('game_id', 0);
        $userId = request()->input('user_id', '');
        $lat = request()->input('lat', 0);
        $lng = request()->input('lng', 0);
        //查询地点
        $QqMap = new QqMap();
        $info = $QqMap->geocoder($lat, $lng);

        $game = Reservation::find($gameId);
        if (!$game || $game->status != 20) {
            return response()->json(['recode' => 0, 'msg' => '未找到挑战']);
        }
        if ($game->play_a != $userId && $game->play_b != $userId) {
            return response()->json(['recode' => 0, 'msg' => '投诉人错误']);
        }
        $game->abnormal_id = $userId;
        $game->abnormal_address = $info['result']['address'];
        $game->status = 40;
        $game->save();
        return response()->json(['recode' => 1, 'msg' => '提交成功']);

    }
    public function cancelGame()
    {
        $gameId = request()->input('game_id', 0);
        $game = Reservation::find($gameId);
        if (!$game || $game->status != 10) {
            return response()->json(['recode' => 0, 'msg' => '未找到挑战']);
        }
        $game->status = 0;
        $game->save();
        return response()->json(['recode' => 1, 'msg' => '取消成功']);

    }

    public function rejectGame()
    {
        $gameId = request()->input('game_id', 0);
        $game = Reservation::find($gameId);
        if (!$game || $game->status != 10) {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }
        $game->status = 30;
        $game->save();
        //发送通知
        $this->dispatch((new SendReservationReject($game)));

        return response()->json(['recode' => 1, 'msg' => '拒绝成功']);

    }
    public function applyGame()
    {
        $gameId = request()->input('game_id', 0);
        $applyId = request()->input('apply_id', 0);
        $game = Reservation::find($gameId);
        if (!$game || $game->status != 10) {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }
        if ($game->type == 1) {
            $applyBLL = new Personal($applyId);
        } else {

        }
        $vaildApply = $applyBLL->validateReservationB($game->score);
        if ($vaildApply['status']) {
            $game->play_b = $applyBLL->id;
        } else {
            return response()->json(['recode' => 0, 'msg' => $vaildApply['msg']]);
        }
        $game->status = 20;
        $game->save();
        //发送通知
        $this->dispatch((new SendReservationSuccess($game)));

        return response()->json(['recode' => 1, 'msg' => '应战成功']);
    }

}
